package com.byxy.muxinnetty.control;

import com.byxy.muxinnetty.Bo.UserBo;
import com.byxy.muxinnetty.enums.OperatorFriendRequestTypeEnum;
import com.byxy.muxinnetty.enums.SearchFriendsStatusEnum;
import com.byxy.muxinnetty.pojo.ChatMsg;
import com.byxy.muxinnetty.pojo.Users;
import com.byxy.muxinnetty.service.FastDFSService;
import com.byxy.muxinnetty.service.UserService;
import com.byxy.muxinnetty.utils.IMoocJSONResult;
import com.byxy.muxinnetty.utils.MD5Utils;
import com.byxy.muxinnetty.vo.MyFriendsVO;
import com.byxy.muxinnetty.vo.UsersVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("u")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private FastDFSService fastDFSService;

    /**
     * 登录注册
     *
     * @param users
     * @return
     * @throws Exception
     */
    @PostMapping("/registOrLogin")
    public IMoocJSONResult registOrLogin(@RequestBody Users users) throws Exception {

        //1.判断用户名和密码不能为空
        if (StringUtils.isBlank(users.getUsername()) || StringUtils.isBlank(users.getPassword())) {
            return IMoocJSONResult.errorMsg("用户名或密码不能为空...");
        }

        //2.判断用户名是否存在，如果存在就登录，如果不存在则注册
        boolean usernameIsExist = userService.queryUsernameIsExist(users.getUsername());
        Users userResult = null;

        if (usernameIsExist) {
            //2.1 登录
            userResult = userService.queryUserForLogin(users.getUsername(), MD5Utils.getMD5Str(users.getPassword()));
            if (userResult == null) {
                return IMoocJSONResult.errorMsg("用户名或密码不正确");
            }
        } else {
            //2.2 注册
            users.setNickname(users.getUsername());
            users.setFaceImage("image/cat.jpg");
            users.setFaceImageBig("image/cat.jpg");
            users.setPassword(MD5Utils.getMD5Str(users.getPassword()));

            userResult = userService.saveUser(users);
        }

        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(userResult, usersVO);

        return IMoocJSONResult.ok(usersVO);
    }

    /**
     * 更新头像
     *
     * @param userId
     * @param file
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/upload", headers = {"content-type=multipart/form-data"})
    public String uploadFace(String userId, MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path = fastDFSService.upload(file);

        System.out.println(path);

        String fdsServer = "http://192.168.31.99:88/";

        Users users = new Users();
        users.setId(userId);
        users.setFaceImageBig(fdsServer + path);
        users.setFaceImage(fdsServer + path);

        Users userInfo = userService.uppdateUserInfo(users);

        return fdsServer + path;
    }

    /**
     * 设置用户名
     *
     * @param userBo
     * @return
     */
    @PostMapping(value = "/setNickName")
    public IMoocJSONResult setNickName(@RequestBody UserBo userBo) {
        Users users = new Users();
        users.setId(userBo.getUserId());
        users.setNickname(userBo.getNickName());

        System.out.println(userBo.getUserId() + "---" + userBo.getNickName());

        Users userInfo = userService.uppdateUserInfo(users);

        return IMoocJSONResult.ok(userInfo);
    }

    /**
     * 收搜好友,根据账号做匹配查询而不是模糊查询
     *
     * @return
     */
    @PostMapping(value = "/search")
    public IMoocJSONResult search(String myUserId, String friendUsername) {
        if (StringUtils.isBlank(myUserId) || StringUtils.isBlank(friendUsername)) {
            return IMoocJSONResult.errorMsg("");
        }
        // 前置条件 1-搜索的用户如果不存在，返回[没有此用户]
        // 前置条件 2-搜索账号是你自己，返回[不能添加你自己]
        // 前置条件 3-搜索的朋友已经是你的好友，返回[该用户已经是你的好友]
        Integer status = userService.preconditionSearchFriends(myUserId, friendUsername);
        if (status == SearchFriendsStatusEnum.SUCCESS.status) {
            Users users = userService.queryUserInfoByUsername(friendUsername);
            UsersVO usersVO = new UsersVO();
            BeanUtils.copyProperties(users, usersVO);
            return IMoocJSONResult.ok(usersVO);
        } else {
            String errorMSg = SearchFriendsStatusEnum.getMsgByKey(status);
            return IMoocJSONResult.errorMsg(errorMSg);
        }
    }

    /**
     * 发送添加好友请求
     *
     * @return
     */
    @PostMapping(value = "/addFriendRequest")
    public IMoocJSONResult addFriendRequest(String myUserId, String friendUsername) {
        if (StringUtils.isBlank(myUserId) || StringUtils.isBlank(friendUsername)) {
            return IMoocJSONResult.errorMsg("");
        }
        // 前置条件 1-搜索的用户如果不存在，返回[没有此用户]
        // 前置条件 2-搜索账号是你自己，返回[不能添加你自己]
        // 前置条件 3-搜索的朋友已经是你的好友，返回[该用户已经是你的好友]
        Integer status = userService.preconditionSearchFriends(myUserId, friendUsername);
        if (status == SearchFriendsStatusEnum.SUCCESS.status) {
            userService.sendFriendRequest(myUserId, friendUsername);
        } else {
            String errorMSg = SearchFriendsStatusEnum.getMsgByKey(status);
            return IMoocJSONResult.errorMsg(errorMSg);
        }

        List<MyFriendsVO> myFriendsVOS = userService.queryMyFriends(myUserId);
        return IMoocJSONResult.ok(myFriendsVOS);
    }

    @PostMapping("/queryFriendRequest")
    public IMoocJSONResult queryFriendRequest(String userId) {
        if (StringUtils.isBlank(userId)) {
            return IMoocJSONResult.errorMsg("");
        }
        // 查询用户接受到的朋友申请
        return IMoocJSONResult.ok(userService.queryFriendRequestList(userId));
    }

    @PostMapping("/openFriendRequest")
    public IMoocJSONResult queryFriendRequest(String acceptUserId, String sendUserId, Integer operType) {
        // 1. acceptUserId sendUserId operType 判断不能为空
        if (StringUtils.isBlank(acceptUserId) || StringUtils.isBlank(sendUserId) || operType == null) {
            return IMoocJSONResult.errorMsg("");
        }

        // 2.如果operType,没有对应的枚举值,则直接抛出空错误信息
        if (StringUtils.isBlank(OperatorFriendRequestTypeEnum.getMsgByKey(operType))) {
            return IMoocJSONResult.errorMsg("");
        }

        if (operType == OperatorFriendRequestTypeEnum.IGNORE.type) {
            // 3.判断如果忽略请求，则直接删除好友请求的数据库表记录
            userService.deleteFriendRequest(acceptUserId, sendUserId);
        } else if (operType == OperatorFriendRequestTypeEnum.PASS.type) {
            // 4.判断如果是通过好友请求,则互相增加好友记录到数据库对应的表,然后删除好友请求记录
            userService.passFriendRequest(acceptUserId, sendUserId);
        }
        // 查询用户接受到的朋友申请
        return IMoocJSONResult.ok();
    }

    /**
     * 查询我的好友列表
     *
     * @param userId
     * @return
     */
    @PostMapping("/myFriends")
    public IMoocJSONResult myFriends(String userId) {
        // 1. acceptUserId sendUserId operType 判断不能为空
        if (StringUtils.isBlank(userId)) {
            return IMoocJSONResult.errorMsg("");
        }

        // 2.数据库查询好友
        List<MyFriendsVO> myFriendsVOS = userService.queryMyFriends(userId);

        return IMoocJSONResult.ok(myFriendsVOS);
    }

    /**
     * 用户手机端获取未签收的消息列表
     * @param acceptUserId
     * @return
     */
    @PostMapping("/getUnReadMsgList")
    public IMoocJSONResult getUnReadMsgList(String acceptUserId) {
        // 1. acceptUserId 判断不能为空
        if (StringUtils.isBlank(acceptUserId)) {
            return IMoocJSONResult.errorMsg("");
        }

        // 2.查询列表
        List<ChatMsg> unReadMsgList = userService.getUnReadMsgList(acceptUserId);

        return IMoocJSONResult.ok(unReadMsgList);
    }
}
